<template>
	<view class="container">
		<view class="header">
			<!-- 搜索栏 begin -->
			<!-- 			<view class="search-box">
				<view class="search-input" @tap="showSearch=true">
					<image src="/static/images/common/search-icon.png" class="search-icon"></image>
					<view>搜索</view>
				</view>
			</view> -->
			<!-- 搜索栏 end -->
			<view class="center">
				<view class="store">
					<view class="title">
						<image :src="orderType == 'takein' ? 
								'/static/images/common/star_normal.png' : 
								'/static/images/order/order_icon_address.png'"
						 class="left-icon" />
						<!-- 为了测试方便，这里使用静态店铺数据 -->
						<view  class="address">{{ orderType == 'takeout' ? address.AddrComplete_address : shop.name }}</view>
						<image src="/static/images/common/black_arrow_right.png" class="right-icon" @click="showShopPage()"></image>
					</view>
					<!-- 外卖&自取switch begin -->
					<view class="buttons">
						<button type="default" class="button" :class="{active: orderType == 'takein'}" plain hover-class="none" @tap="switchOrderType">
							自取
						</button>
						<button type="default" class="button" :class="{active: orderType == 'takeout'}" plain hover-class="none" @tap="switchOrderType">
							外卖
						</button>
					</view>
					<!-- 外卖&自取switch end -->
				</view>
				<view class="location">距离您{{shop.distanceL}}km</view>
			</view>
			<!-- 滚动公告栏 begin -->
			<view class="notices">
				<swiper class="swiper" autoplay vertical :interval="3000" :duration="1000" circular>
					<swiper-item v-for="(notice, index) in notices" :key="index">
						<view class="swiper-item">
							<image :src="notice.BrdcCoverPic" class="image"></image>
							<view class="content">{{ notice.BrdcTitle }}</view>
						</view>
					</swiper-item>
				</swiper>
				<view class="more" @click="togoPage('/pages/my/components/boardcast/boardcast')">
					<text>更多</text>
					<image src="/static/images/common/gray_arrow_down.png" class="down-icon"></image>
				</view>
			</view>
		</view>
		<!-- 滚动公告栏 end -->
		<view class="main">
			<!-- 左侧菜单 begin -->
			<scroll-view class="menu-bar" scroll-y scroll-with-animation>
				<view class="wrapper">
					<view class="menu-item" @tap="handleMenuSelected(category.id)" :class="{active: currentCategoryId == category.id}"
					 v-for="(category, index) in categories" :key="index">
						<image :src="category.category_image_url" class="image" mode="widthFix"></image>
						<view class="title">{{ category.name }}</view>
					</view>
				</view>
			</scroll-view>
			<!-- 左侧菜单 end -->
			<!-- 右侧商品列表 begin -->
			<scroll-view class="product-section" scroll-y scroll-with-animation :scroll-top="productsScrollTop" @scroll="productsScroll">
				<view class="wrapper">
					<view id="ads">
						<!-- 广告栏1 begin -->
						<swiper class="ads1" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" circular>
							<swiper-item v-for="(ad, index) in ads1" :key="index">
								<image :src="ad.AdsImg" class="w-100" mode="widthFix"></image>
							</swiper-item>
						</swiper>
						<!-- 广告栏1 end -->
					</view>
					<!-- 商品 begin -->
					<view class="products-list" v-for="(category, index) in categories" :key="index" :id="`products-${category.id}`">
						<view class="category-name">{{ category.name }}</view>
						<view class="products">
							<view class="product" v-for="(product, key) in category.products" :key="key" @tap="showProductDetailModal(product)">
								<image :src="product.name_image" mode="widthFix" class="image"></image>
								<view class="content">
									<view class="name">{{ product.name }}</view>
									<view class="labels">
										<view class="label" :style="{color: label.label_color, background: $util.hexToRgba(label.label_color, 0.2)}"
										 v-for="label in product.labels" :key="label.id">{{ label.name }}</view>
									</view>
									<view class="description">{{ product.description }}</view>
									<view class="price">
										<view>￥{{ product.price }}</view>
										<actions :materials-btn="!product.is_single" @materials="showProductDetailModal(product)" :number="productCartNum(product.id)"
										 @add="handleAddToCart(product)" @minus="handleMinusFromCart(product)" />
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 商品 end -->
				</view>
			</scroll-view>
			<!-- 右侧商品列表 end -->
		</view>
		<!-- 商品详情 modal begin -->
		<product-modal :product="product" :visible="productModalVisible" @cancel="closeProductDetailModal" @add-to-cart="handleAddToCartInModal" />
		<!-- 商品详情 modal end -->
		<!-- 购物车栏 begin -->
		<cart-bar :cart="cart" @add="handleAddToCart" @minus="handleMinusFromCart" @clear="clearCart" @pay="pay" />
		<!-- 购物车栏 end -->
		<search :show="showSearch" :categories="categories" @hide="showSearch=false" @choose="showProductDetailModal"></search>
		<!-- 登录popup -->
		<login-popup ref="loginPopup"></login-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import Actions from './components/actions/actions.vue'
	import CartBar from './components/cartbar/cartbar.vue'
	import ProductModal from './components/product-modal/product-modal.vue'
	import cartPopup from './components/cart-popup/cart-popup.vue'
	import Search from './components/search/search.vue'
	import loginPopup from '../my/components/login-popup.vue'

	export default {
		components: {
			Actions,
			CartBar,
			ProductModal,
			cartPopup,
			Search,
			loginPopup,
		},
		data() {
			return {
				categories: [],
				cart: [],
				product: {},
				currentCategoryId: 0,
				notices: [],
				ads1: [],
				productModalVisible: false,
				cartPopupShow: false,
				productsScrollTop: 0,
				showSearch: false,
				showShop: false
			}
		},
		computed: {
			...mapState(['orderType', 'address', 'shop', 'isLogin', 'userInfo','isChangeShop']),
			productCartNum() { //计算单个饮品添加到购物车的数量
				return id => this.cart.reduce((acc, cur) => {
					if (cur.id === id) {
						return acc += cur.number
					}
					return acc
				}, 0)
			}
		},
		onShow(){
			if(this.isChangeShop){
				this.initPage(this.shop.id);
				this.SET_CHANGESHOP(false);
			}
		},
		async onLoad(options) {
			//二维码携带店铺id 否则使用本地缓存  都不存在  就使用默认店铺id
			let coid = options.scene;
			if (coid != undefined && coid > 0){
				
			}else{
				coid=0;
			}
			this.initPage(coid);
			
		},
		methods: {
			...mapMutations(['SET_ORDER_TYPE', 'SET_SHOP','SET_CHANGESHOP']),
			togoPage(url) {
				uni.navigateTo({
					url: url
				})
			},
			initPage(coid){
				let new_coid=0;
				if ( coid > 0) {
					uni.setStorageSync("coid", coid);
					new_coid=coid;
				} else {
					let coid = uni.getStorageSync('coid');
				    new_coid = (coid != undefined && coid > 0) ? coid : 4;
					uni.setStorageSync("coid", new_coid);
				}
				//根据coid 获取店铺数据。
				this.getShopInfoByCoId(new_coid);
				
				console.log(`do------------onLoad`)
				//获取分类数据
				this.getCategories(new_coid);
				//获取广告数据
				this.getAds();
				//获取 播报数据
				this.getBoardcast();
				//判断用户是否登入
				setTimeout(()=>{
					this.openLoginPopup();
				},1000);
			},
			//判断用户是否登入
			openLoginPopup() {
				if(this.isLogin) {
					return
				}
				this.$refs['loginPopup'].open()
			},
			//切换店铺
			showShopPage() {
				//this.showShop=true;
				uni.navigateTo({
					url: "/pages/index/components/shop/shop"
				});
			},
			//根据coid 获取店铺数据。
			getShopInfoByCoId(coid) {
				let that = this;
				let whe = `areaId=&shopName=&coid=${coid}`;
				let cateOp = {
					url: `api/Lx_Self_CoInfo/UI_GetPageData?${whe}`,
					data: {}
				}

				this.$request.Post(cateOp, (ret) => {
					if (ret.data.length > 0) {
						let e = ret.data[0];
						let currStoreData = {
							id: e.coId,
							name: e.coName,
							address: e.coAddr,
							tel: e.coPhone,
							bessuniesTime: e.coBusinessHours,
							latitude: e.coLatitude,
							longitude: e.coLongitude,
							distanceL: 2.3
						}

						that.SET_SHOP(currStoreData);
						if(e.auditstatus==0){
							uni.showModal({
								content: e.auditreason+",请还一家店铺看看吧~",
								confirmColor: '#DBA871',
								success: res => {
									if (res.confirm) {
										this.togoPage('/pages/index/components/shop/shop')
									}
								}
							})
						}
					
					}
				});
			},
			//获取分类数据
			getCategories(coid) {
				let that = this;
				let cateOp = {
					url: `api/Lx_Self_Categories/UI_GetCategories?coid=${coid}`,
					data: {}
				}

				this.$request.Post(cateOp, (ret) => {
					if (ret.data.length > 0) {
						that.categories = ret.data;
						that.categories.map(e => {
							e.products.map(n => {
								n.images.map(img => {
									img.url = that.$request.setImgUrl(img.url, "123");
									return img;
								})
								n.name_image = that.$request.setImgUrl(n.name_image);
								return n;
							});

							return e;
						});
						that.currentCategoryId = that.categories.length && that.categories[0].id
						that.$nextTick(() => that.calcSize())
					}
				});
			},

			//获取广告数据
			getAds() {
				let that = this;
				let whe=[];
				whe.push({
					"name": "AdsType",
					"value": 2,
					"displayType": 'text'
				});
				let cateOp = {
					url: "api/Lx_Self_Ads/UI_GetPageData",
					data: {
						"page": 1,
						"rows": 20,
						"sort": "CreateDate",
						"order": "desc",
						"wheres": JSON.stringify(whe)
					}
				}

				this.$request.Post(cateOp, (ret) => {
					if (ret.rows.length > 0) {
						that.ads1 = ret.rows;
						that.ads1.map(n => {
							n.AdsImg = that.$request.setImgUrl(n.AdsImg,"ttt");
							return n;
						});

						that.$nextTick(() => that.calcSize())
					}
				});
			},
			//获取 播报数据
			getBoardcast() {
				let that = this;
				let cateOp = {
					url: "api/Lx_Self_Boardcast/UI_GetPageData",
					data: {}
				}

				this.$request.Post(cateOp, (ret) => {
					if (ret.rows.length > 0) {
						that.notices = ret.rows;
						that.notices.map(n => {
							n.BrdcCoverPic = that.$request.setImgUrl(n.BrdcCoverPic);
							return n;
						});
						that.$nextTick(() => that.calcSize())
					}
				});
			},

			switchOrderType() {
				if (this.orderType === 'takein') {
					uni.navigateTo({
						url: '/pages/addresses/addresses'
					})
				} else {
					this.SET_ORDER_TYPE('takein')
				}
			},
			
			handleAddToCart(product) { //添加到购物车
				const index = this.cart.findIndex(item => {
					if (!product.is_single) {
						return (item.id == product.id) && (item.materials_text == product.materials_text)
					} else {
						return item.id === product.id
					}
				})

				if (index > -1) {
					this.cart[index].number += (product.number || 1)
					return
				}

				this.cart.push({
					id: product.id,
					cate_id: product.category_id,
					name: product.name,
					price: product.price,
					number: product.number || 1,
					image: product.name_image, // product.images[0].url,
					is_single: product.is_single,
					materials_text: product.materials_text || '',
					selectedMaterials:product.selectedMaterials||[]
				})
			},
			handleMinusFromCart(product) { //从购物车减商品
				let index
				if (product.is_single) {
					index = this.cart.findIndex(item => item.id == product.id)
				} else {
					index = this.cart.findIndex(item => (item.id == product.id) && (item.materials_text == product.materials_text))
				}
				this.cart[index].number -= 1
				if (this.cart[index].number <= 0) {
					this.cart.splice(index, 1)
				}
			},
			showProductDetailModal(product) {
				this.product = product
				this.productModalVisible = true
			},
			handleAddToCartInModal(product) {
				this.handleAddToCart(product)
				this.closeProductDetailModal()
			},
			closeProductDetailModal() {
				this.productModalVisible = false
				this.product = {}
			},
			openCartDetailsPopup() {
				this.$refs['cartPopup'].open()
			},
			clearCart() {
				this.cart = []
			},
			handleMenuSelected(id) {
				this.productsScrollTop = this.categories.find(item => item.id == id).top
				this.$nextTick(() => this.currentCategoryId = id)
			},
			productsScroll({
				detail
			}) {
				const {
					scrollTop
				} = detail
				let tabs = this.categories.filter(item => item.top <= scrollTop).reverse()
				if (tabs.length > 0) {
					this.currentCategoryId = tabs[0].id
				}
			},
			calcSize() {
				let h = 0
				let view = uni.createSelectorQuery().select('#ads')
				view.fields({
					size: true
				}, data => {
					h += Math.floor(data.height)
				}).exec()

				this.categories.forEach(item => {
					let view = uni.createSelectorQuery().select(`#products-${item.id}`)
					view.fields({
						size: true
					}, data => {
						item.top = h
						h += Math.floor(data.height)
						item.bottom = h
					}).exec()
				})
			},
			pay() {
				uni.setStorageSync('cart', this.cart)
				uni.navigateTo({
					url: '/pages/pay/pay'
				})
			}
		}
	}
</script>

<style lang="scss">
	@import './index.scss';
</style>
